<?php
/**
 * 卡片管理次卡和消费卡
 */
namespace app\canteen\admin;

use app\common\builder\button\Custom;
use app\common\builder\ZBuilder;
use app\common\model\StCard as StCardModel;
use app\common\model\StUser;
use think\Image;

class StCard extends Base
{
    public function index()
    {
        $map = $this->getMap();
        if (UID > 1) $map =['comid'=>COMID,'status'=>1];
        $order = $this->getOrder('id desc');
        $list = StCardModel::where($map)->order($order)->paginate();
        $page = $list->render();
        return ZBuilder::make('table')
            ->addColumns([
//                ['id', 'ID'],
                ['uid', '持卡人', self::getStUser()],
                ['card_code', '卡号', 'text'],
                ['card_type', '卡类型', 'text','',self::$cardType],
                //['comid', '单位', 'text'],
                ['create_time', '创建时间', 'date'],
                ['status', '状态','status'],
                ['right_button', '操作', 'btn']
            ])
            //批量添加顶部按钮
            ->addTopButtons('add,enable,disable')
            ->addTopButton('custom', Custom::button('recharge'), ['area' => ['550px','55%']]) // 添加授权按钮如果需要以弹出层的方式打开页面的话，只需将第三个参数设置为true即可
            ->addRightButton('custom', Custom::button('details','right'),true)//详情按钮
            // 批量添加右侧按钮
            ->addRightButtons(['edit'=>['title'=>'充值']])
            //设置排序
            ->addOrder('id,create_time')
            // 设置搜索参数
            ->setSearch(['card_code' => '卡号','id'=>'ID号'])
            //设置筛选
            ->addFilterList('card_type', self::$cardType)
            ->addFilterList('status', [0=>'禁用', 1=>'启用'])
            ->setTableName('st_card')
            ->setRowList($list)
            ->setPages($page)
            ->fetch();
    }

    public function recharge($ids=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data,'StCard.recharge');
            if(true !== $result) $this->error($result);

            if ((new StCardModel())->syncard($data)) {
                $this->success('批量充值成功', null, '_parent_reload');
            } else {
                $this->error('批量充值失败');
            }
        }else{
            return ZBuilder::make('form')
                ->setPageTitle('批量充值')
                ->addFormItems([
                    ['hidden', 'id',$ids],
                    ['radio', 'card_type', '选择充值卡类型', '', self::$cardType],
                    ['number', 'total_amount', '充金额','<code>按月充值；单位:元;0~999</code>','',0,1000,1],
                    ['number', 'total_cishu', '充次数','<code>按月充次；单位:次;0~100</code>','',0,100,1],
                    ['date', 'valid_start_time', '有效开始时间', '<code>充值金额或次数有效开始时间</code>', format_date(time())],
                    ['date', 'valid_end_time', '有效截至时间', '<code>充值金额或次数有效结束时间</code>'],
                ])
                ->setTrigger([
                    ['card_type', 'CC', 'total_cishu'],
                    ['card_type', 'FC', 'total_amount'],
                ])
               // ->layout(['total_amount'=>6,'total_cishu'=>6])
                ->fetch();
        }
    }

    //新增
    public function add()
    {
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'StCard');
            if(true !== $result) $this->error($result);
            $user   = StUser::get($data['uid']);
            $Company=  \app\common\model\Company::get($user->comid);
            $data['card_code']=self::getcardCode($data['card_type']);
            $data['user_name']=$user->user_name;

            $path = plugin_action('Qrcode/GeneratePoster/qrcode',  $data['card_code']);
            $arr=[
                'file_dir'=> $path['file_dir'],
                'file_name'=> $path['file_name'],
                'qrCodeImg_path'=> $path['file_path'],
                'backgroundImg_path'=> config('static_path').'/admin/img/beijingtu.jpg',
                'card_code'=>$data['card_code'],
            ];
            $filename= plugin_action('Qrcode/GeneratePoster/generate', [$arr]);
            $data['path']='/uploads/images/'.$path['dir_name'].'/'.$filename;
            $watermark=[
                [
                    'path'=> config('upload_path').'/images/'.$path['dir_name'].'/'.$filename,
                    'text'=> $Company->company_name,
                    'offset'=> [0,75]],
                [
                    'path'=> config('upload_path').'/images/'.$path['dir_name'].'/'.$filename,
                    'text'=> $user->user_name,
                    'offset'=> [0,110]],
            ];
            foreach ($watermark as $value){
                self::watermark($value);
            }
//           dump($data); exit();
            if ((new StCardModel())->syncard($data)) {
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }

        return ZBuilder::make('form')
            ->setPageTitle('温馨提示 : 请先选择卡类型后在充值 提交后不能修改卡类型')
            ->addGroup(
                [
                    '餐卡' =>[
                        ['hidden', 'comid', COMID],
                        ['select', 'uid', '持卡人','<code>*必填项</code>',self::getStUser()],
                        ['radio', 'card_type', '卡类型', '', self::$cardType,'FC'],
                        ['radio', 'status', '立即启用', '', ['否', '是'], 1]
                    ],
                    '充值' =>[
                        ['number', 'total_amount', '充金额','<code>按月充值；单位:元;0~999</code>','',0,1000,1],
                        ['number', 'total_cishu', '充次数','<code>按月充次；单位:次;0~100</code>','',0,100,1],
                        ['date', 'valid_start_time', '有效开始时间', '<code>充值金额或次数有效开始时间</code>', format_date(time())],
                        ['date', 'valid_end_time', '有效截至时间', '<code>充值金额或次数有效结束时间</code>'],
                    ]
                ]
            )
            ->setTrigger([
                ['card_type', 'CC', 'total_cishu'],
                ['card_type', 'FC', 'total_amount'],
            ])
            ->layout(['uid'=>3,'card_code'=>7,'total_amount'=>7,'total_cishu'=>7,'valid_start_time'=>7,'valid_end_time'=>7])
            ->fetch();

    }

    //编辑
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = $this->validate($data, 'StCard.edit');
            if(true !== $result) $this->error($result);
            if ((new StCardModel())->syncard($data)) {
                $this->success('充值成功', 'index');
            } else {
                $this->error('充值失败');
            }
        }
        $info = StCardModel::get($id);
        return ZBuilder::make('form')
            ->setPageTitle('充值操作')
            ->addFormItems([
                ['hidden', 'id'],
                ['hidden', 'card_type', '卡类型', '', self::$cardType],
                //['hidden', 'uid', '持卡人','<code>*必填项</code>',self::getStUser()],
                ['static', 'card_code', '卡号'],
                ['number', 'total_amount', '充金额','<code>按月充值；单位:元;0~999</code>','',0,1000,1],
                ['number', 'total_cishu', '充次数','<code>按月充次；单位:次;0~100</code>','',0,100,1],
                ['date', 'valid_start_time', '有效开始时间', '<code>充值金额或次数有效开始时间</code>', format_date(time())],
                ['date', 'valid_end_time', '有效截至时间', '<code>充值金额或次数有效结束时间</code>'],
            ])
            ->setTrigger([
                ['card_type', 'CC', 'total_cishu'],
                ['card_type', 'FC', 'total_amount'],
            ])
            ->setFormdata($info)
            ->layout(['uid'=>3,'card_code'=>7,'total_amount'=>7,'total_cishu'=>7,'valid_start_time'=>7,'valid_end_time'=>7])
            ->fetch();
    }

    public function details($id = null){
        if ($id === null) $this->error('缺少参数');
        $data = StCardModel::get($id);
        $data['card_type']= self::$cardType[$data['card_type']];
        $this->assign('card',$data);
        return $this->fetch();
    }


    //生成卡号
    public static function getcardCode($type){
        return $type.strtoupper(dechex(date('m'))).date('d').
            substr(time(),-5).substr(microtime(),2,5).sprintf('d',rand(0,99));
    }

    //添加水印
    public static function watermark($payload=[]){
        $arr=[
            'path'  => config('upload_path') . DIRECTORY_SEPARATOR . 'images/20221117/HB20221117150134.jpg',//图片路径
            'text'  => '我是水印文字哦哇',	//加的文字
            'font'  => config('static_path').'/admin/fonts/msyh.ttf',	//字体文件路径
            'size'  => 12,	    // 字号，单位是像素
            'color' => '#000000',	// 文字颜色 #626262
            'locate'=> 2,   // 文字写入位置
            'offset'=> [0,65],	// 文字相对当前位置的偏移量
            'angle' => 0,   // 倾斜度
        ];
        $array = array_merge($arr,$payload);
        $watermark_pos = '9';//位置
        $watermark_alpha = '50';// 水印透明度
        $image = Image::open($array['path']);
        $image->text($array['text'],$array['font'], $array['size'], $array['color'], $array['locate'], $array['offset'], $array['angle']);
        $image->water($array['path'], $watermark_pos, $watermark_alpha);
        // 保存水印图片，覆盖原图
        $image->save($array['path']);
    }

}